import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import StudentList from '../views/StudentList.vue'
import StudentForm from '../views/StudentForm.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/students',
    name: 'StudentList',
    component: StudentList,
    meta: { requiresAuth: true }
  },
  {
    path: '/students/add',
    name: 'StudentAdd',
    component: StudentForm,
    meta: { requiresAuth: true, roles: ['ADMIN'] }
  },
  {
    path: '/students/edit/:id',
    name: 'StudentEdit',
    component: StudentForm,
    meta: { requiresAuth: true, roles: ['ADMIN'] }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const user = JSON.parse(localStorage.getItem('user') || 'null')
  const token = localStorage.getItem('token')

  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.roles && user && !to.meta.roles.includes(user.role)) {
    next('/')
  } else {
    next()
  }
})

export default router 